Skip to content

fix(stacked_did): anticipation-aware clean controls and survey-inference fixes - #923

Merged
igerber merged 15 commits into
mainfrom
fix/stacked-did-anticipation-survey
Nov 27, 2026
Merged

igerber merged 15 commits into
mainfrom
fix/stacked-did-anticipation-survey

Conversation

@igerber

@igerber igerber commented Nov 27, 2026 •

Copy link
Copy Markdown
Owner

Summary

Split out of #920 (the Staggered family tutorials), whose review surfaced these StackedDiD defects. All of them are on main today; #920 goes back to documentation only once this merges.

Clean controls under anticipation

  • With anticipation > 0, a later adopter stayed in an event's control pool through periods in which it was already responding. On a noiseless balanced panel (cohorts 3, 6 and never-treated, an effect of 2 starting one period before adoption, kappa_pre = kappa_post = 2, anticipation = 1) the fit returned 1.5 at event time 2 and 1.875 overall; both are now 2 exactly.
  • The cutoff is A_s > a + kappa_post + anticipation, plus kappa_pre under "strict", applied by one helper in the inclusion check and the stack builder. Fits with anticipation=0 or never-treated controls are unchanged, and the R-parity panels regenerate byte-identical.
  • New StackedDiDResults.control_cutoff_includes_anticipation records the rule (True on every fit, None on a result saved by an earlier version). BusinessReport and DiagnosticReport state the adjusted cutoff only when it is recorded, and otherwise show the earlier cutoff labelled unverified.

Survey inference (Taylor linearization)

  • Refusal: a fit in which the anticipation term leaves a later cohort out of every sub-experiment raises NotImplementedError. The design is re-resolved on the stacked rows, so that cohort's PSUs or strata can leave the variance (stratified census: SE 0.136 with 9 df where the full design gives SE 0 with 15 df).
  • Implicit PSU: a design that names no psu uses each original unit as its PSU for either cluster setting. Under cluster="unit_subexp" the fit used (unit, sub-experiment) pairs, which duplicate sampled units: SE 0 with 21 df where the sampled units give SE 0.07906 with 15. Standard errors change for survey fits that combined cluster="unit_subexp" with a design naming no psu.
  • Validation: implicit unit PSUs now get the checks an explicit psu gets, against the full supplied sample and not only the units that reach the stack. A single-unit stratum warns, and an FPC below a stratum's unit count raises.
  • Zero degrees of freedom: when n_PSU - n_strata = 0 the fit returns NaN t-statistics, p-values and intervals with a warning. It clamped the df to 1 and reported t(1) inference (p = 0.079 on a six-unit, six-stratum panel).
  • Empty panel: fit() on a panel with no rows raises a descriptive ValueError (it raised "cannot convert float NaN to integer", or IndexError with an FPC column).

Consumers of undefined inference

  • plot_event_study(results) rebuilt intervals from the standard error for rows whose stored interval is missing or NaN at either endpoint. Those rows now get no interval, on the generic route and the dCDH route (effects and placebos), as the aggregate("event_study") container already did.
  • BusinessReport's zero-df caveat follows what the fit stored: interval availability from the stored bounds, significance from the stored p-value.

Not fixed here (logged in TODO.md)

  • SunAbraham has the same clamp to 1 at zero survey df. Removing it alone leaves its cell-level inference on a normal-theory fallback, so it needs its own change.
  • Full-design (domain) survey inference for units outside the stack, which would lift the three survey refusals.
  • On the Plotly backend the band still fills across the position of a row without an interval when its neighbours have one, and the raw-results route's reference handling (the -1 fallback, the int() cast of a declared reference, mixed-type horizon labels) is unchanged. Both are documented in the Registry and tracked for a dedicated plotting change.

Methodology references (required if estimator / math changes)

  • Method name(s): StackedDiD clean-control selection and Taylor-linearized survey inference.
  • Paper / source link(s): Wing, C., Freedman, S. M., & Hollingsworth, A. (2024). Stacked Difference-in-Differences. NBER Working Paper 32054. http://www.nber.org/papers/w32054
  • Any intentional deviations from the source (and why): the paper assumes no anticipation, so the anticipation-adjusted cutoff is a library extension. It and the survey rules are recorded in docs/methodology/REGISTRY.md as - **Note (clean controls under anticipation):**, - **Note (survey PSU without an explicit psu):** and - **Note (zero survey degrees of freedom):** in the StackedDiD section, and - **Note (undefined stored inference on the raw-results routes):** under Event Study Plotting.

Validation

  • Tests added/updated: tests/test_stacked_did.py (TestCleanControlAnticipation, TestCleanControlAnticipationSurvey), tests/test_business_report.py, tests/test_target_parameter.py, tests/test_visualization.py (TestPlotEventStudyUndefinedStoredInference, TestPlotEventStudyRawDCDHUndefinedInference, TestPlotEventStudyFittedUndefinedRow). The clean-control regression tests fail without the fix. 4535 passed on each backend across the StackedDiD, survey, dCDH, SunAbraham, plotting, reporting, design and guard test files before the last small commit (report wording and wider plot tests), whose files pass on both backends.
  • Backtest / simulation / notebook evidence (if applicable): every number quoted above was reproduced before the fix and re-measured after it. The Sphinx -W build passes locally.

Security / privacy

  • Confirm no secrets/PII in this PR: Yes

Changelog

  • changelog.d/ fragment added (or N/A - no user-visible change): Yes (changelog.d/20261127-stacked-did-anticipation-survey.md)

@github-actions

Copy link
Copy Markdown

Overall assessment

⛔ Blocker — The new Plotly renderer can display a confidence interval that the fitted survey design withheld.

Executive summary

  • The anticipation-adjusted StackedDiD cutoff follows the documented extension of Wing et al. and is shared by the inclusion check and stack builder.
  • Taylor-linearized survey fits now count each original unit once when no PSU is specified. Zero survey degrees of freedom reach safe_inference unchanged.
  • The new single-row Plotly bar makes fabricated intervals visible on raw dCDH results. The band can also span an estimated row when the plotting fallback labels it as a reference.
  • The changelog check passed. I reproduced the plotting and report behavior with isolated Python checks using test doubles. The environment lacked NumPy and pytest, so full estimator fits and the test suite remain unverified.

Methodology

  • P3 — Documented anticipation extension. Impact. The not-yet-treated rule requires A_s - anticipation > a + kappa_post. The strict rule also keeps the later cohort’s expanded window disjoint. This applies to the entropy-balanced variant through the shared stack builder. At zero anticipation, the ordinary cutoff agrees with the checked-in R reference. Concrete fix. None required. The NBER PDF was unreachable, so the source check used the Registry, the checked-in R reference, and the in-repo review of Ustyuzhanin. docs/methodology/REGISTRY.md:L2600-L2638, benchmarks/R/benchmark_stacked_did.R:L23-L42
  • P3 — Documented survey rules. Impact. Summing stacked scores within the original PSU follows Binder’s design-based variance formulation. The fail-closed rule at zero survey df preserves undefined inference. Concrete fix. None required. diff_diff/stacked_did.py:L1227-L1286, docs/methodology/papers/binder-1983-review.md:L90-L117

Code Quality

  • P0 — Plotly displays a fabricated interval for an isolated dCDH estimate. Impact. The raw dCDH route discards stored pointwise intervals for both effects and placebos, so a finite SE with stored (NaN, NaN) bounds is converted to a normal-theory interval. With L_max=1 and placebo=False, the old transparent polygon had zero area. The new vertical bar makes that invalid interval visible without a plotting warning. Concrete fix. Apply the shared undefined-inference check to dCDH effects and placebos before selecting plot intervals. diff_diff/visualization/_event_study.py:L646-L658, diff_diff/visualization/_event_study.py:L964-L1018, tests/test_survey_dcdh_replicate_psu.py:L998-L1043
  • P1 — The Plotly band can bridge an undefined estimate at event time -1. Impact. The raw route falls back to -1 when the producer supplies no reference marker. With a varying-base event study, -1 can be an estimated placebo. If it has no interval, the renderer treats it as a constraint and fills across it. Concrete fix. Track actual normalization constraints separately from reference-marker styling. Only actual constraints should allow the band to continue across a missing interval. diff_diff/visualization/_event_study.py:L367-L379, diff_diff/visualization/_event_study.py:L628-L639, diff_diff/visualization/_event_study.py:L1067-L1086

Performance

No findings.

Maintainability

  • P2 — The alpha caveat misses rank-one replicate designs. Impact. The new branch recognizes numeric zero, while rank-one replicate designs store df_survey=None. With a requested alpha override, BusinessReport can say the displayed interval remains at native coverage even when both bounds are NaN. Concrete fix. Recognize replicate_method with df_survey=None as undefined df and use the extracted CI bounds to determine whether an interval is available. diff_diff/business_report.py:L745-L805, diff_diff/survey.py:L620-L649

Tech Debt

  • P3 — Tracked follow-ups. Impact. Full-design domain inference and the existing SunAbraham zero-df behavior remain tracked. Concrete fix. No action on these follow-ups is required in this PR. TODO.md:L60-L61

Security

No findings.

Documentation/Tests

The release fragment follows the repository convention and passed the changelog compiler check. changelog.d/20261127-stacked-did-anticipation-survey.md

Path to Approval

  1. Preserve withheld intervals on the raw dCDH route. Add a test with L_max=1, placebo=False, a finite positive SE, and stored NaN bounds. Assert that Plotly draws the estimate marker without an interval.
  2. Split the band at estimated rows regardless of fallback reference styling. Add a raw varying-base case with valid intervals at -2 and 0 and undefined inference at -1. Assert that no polygon spans -1.

…nce fixes

- Clean controls: a later adopter responds from A_s - anticipation, so the
  cutoff is A_s > a + kappa_post + anticipation (plus kappa_pre under
  "strict"), in the inclusion check and the stack builder. A noiseless
  panel with a true effect of 2 gave 1.5 at event time 2 and 1.875 overall.
- Results record the rule (control_cutoff_includes_anticipation); the
  target-parameter description and the BusinessReport assumption block state
  the cutoff a fit used and label an unrecorded one unverified.
- Survey: a fit is refused when the anticipation term takes a sampled unit
  out of the stack; a design without a psu column uses the original unit as
  PSU (never unit-by-sub-experiment pairs) and validates it like an explicit
  PSU; zero survey degrees of freedom gives NaN inference instead of t(1).
- Registry notes, backlog rows, bundled guide and changelog.
…ined in plots and reports

- plot_event_study on a results object rebuilt intervals from the SE for rows
  whose stored interval is NaN with a finite SE (a zero-df survey fit). Those
  rows now plot as points with no interval on every channel.
- BusinessReport names the variance method of a zero-df survey fit and says
  no interval is available.
- StackedDiD shares one window predicate between trimming and the survey
  guard; guide wording says PSUs or strata can leave the design.
…an interval; describe the inference a zero-df fit stored

- The Plotly band skipped a row with no interval and filled across it. It is
  now one polygon per run of rows that carry an interval; a reference row
  does not break the band.
- BusinessReport's zero-df caveat follows the stored interval and p-value:
  "no interval is available" only when the fit stored none.
…a valid interval stays visible

Splitting the Plotly band at rows without an interval can leave a row with a
valid interval on its own; a one-point polygon has no area and was
invisible. Registry and changelog follow the renderer.
…oute; band bridges only real constraints; replicate designs without a df

- The raw dCDH route recomputed intervals from the SE for effects and
  placebos whose stored interval is NaN; the one-row bar made that visible.
  Those rows now plot with no interval.
- The Plotly band continues only across a normalization constraint (a
  reference row with no uncertainty), not across a row merely styled as the
  reference by the -1 fallback.
- BusinessReport treats a replicate design that records no df and stored no
  interval as undefined-df.
…-chosen reference

Reference styling comes from the raw route's -1 fallback when the producer
marks no reference; under a varying base that row is an estimated placebo,
whatever its SE. The band now continues across a row without an interval
only when the caller normalized on it or the producer declared it (container
marks, an is_reference row, a reference_period attribute, the dCDH
reference).
…nstraint only for the horizon it names

A reference a results object declares between horizons (-0.5) was cast to
int and landed on event time 0, an estimated effect, which was then styled
as the reference and, with the new band rule, bridged. The label is kept
as given and verified against the plotted horizon.
…t round-trip; end-to-end plot test on a fitted model
…oss numeric types

Plain == converts an integer reference to float, so a float horizon one away
from it beyond 2**53 compared equal and was styled, and bridged, as the
reference. All reference-label comparisons in plot_event_study go through
one exact comparator (rationals at native precision). The fitted test now
uses a fixture whose shared reference is -0.5.
…rence fix

Keep only: a results object passed directly no longer has intervals rebuilt
from the SE for rows whose stored interval is NaN (generic and dCDH routes).
The Plotly band splitting, the one-row bar, reference provenance and exact
label comparison are taken back out; the Plotly band behavior and the raw
route's reference handling are logged in TODO.md for their own change.
… the full sample; partial intervals; interval vs significance in the report

- StackedDiD: a design naming no PSU has the unit declared as PSU before
  the design is resolved on the supplied panel, so an FPC below a stratum's
  unit count raises even when trimming would bring the stack under it.
- plot_event_study: a stored interval with one missing or NaN endpoint is
  undefined too; a row storing no interval keeps the recomputed one.
- BusinessReport: interval availability follows the stored bounds and
  significance availability the stored p-value, separately.
@igerber
igerber force-pushed the fix/stacked-did-anticipation-survey branch from ddb2629 to acd102d Compare November 27, 2026 15:55
@github-actions

Copy link
Copy Markdown

🔁 AI review rerun (requested by @igerber)

Head SHA: acd102dfece1644af28a135786b9cc6810993d18


Overall assessment

⚠️ Needs changes. The new implicit-PSU path raises IndexError on an empty, unstratified survey panel supplied with an FPC column.

Executive summary

  • The anticipation-adjusted cutoff is consistent with the documented extension of Wing et al. and is shared by the inclusion check and stack builder.
  • Taylor linearization uses the original unit as the implicit PSU. Zero survey degrees of freedom reach safe_inference, which returns NaN for the t-statistic, p-value, and confidence interval.
  • The prior dCDH plotting blocker is resolved. The revision also removes the segmented Plotly renderer that caused the prior reference-row finding. The existing interpolation across missing intervals is documented and tracked.
  • BusinessReport now checks the stored confidence bounds for rank-one replicate designs and describes whether an interval is available.

Methodology

  • P3 · Documented anticipation extension. Impact. A later adopter qualifies only if its response begins after the focal window closes. The strict rule also keeps the two expanded windows disjoint. This applies to both the base and entropy-balanced fits. The zero-anticipation cutoff matches the checked-in R reference. Concrete fix. None required. diff_diff/stacked_did.py:L1680-L1702, docs/methodology/REGISTRY.md:L2636-L2636, benchmarks/R/benchmark_stacked_did.R:L23-L42
  • P3 · Documented survey inference. Impact. Aggregating stacked scores within the original PSU follows Binder’s design-based variance formulation. The new refusal prevents anticipation-induced sample loss from silently changing the survey design used for inference. Concrete fix. None required. diff_diff/stacked_did.py:L691-L711, diff_diff/stacked_did.py:L1239-L1298, docs/methodology/papers/binder-1983-review.md:L86-L104

Code Quality

  • P1 · [Newly identified] Empty unstratified FPC input raises IndexError. Impact. On a zero-row panel with the required columns and SurveyDesign(fpc="N"), fit() now supplies psu=unit before resolving the design. That makes the resolver read fpc_arr[0] on an empty array. Callers handling the documented ValueError will miss this exception. Concrete fix. Reject a zero-row panel with a descriptive ValueError before survey resolution. diff_diff/stacked_did.py:L534-L543, diff_diff/stacked_did.py:L590-L606, diff_diff/survey.py:L383-L395

Performance

No findings.

Maintainability

No open findings. The prior alpha-caveat finding is resolved for both zero and unrecorded replicate degrees of freedom. diff_diff/business_report.py:L745-L812

Tech Debt

  • P3 · Tracked follow-ups. Impact. Plotly can still shade across a missing interval. Full-design survey inference outside the stack and SunAbraham’s zero-df behavior also remain tracked. Concrete fix. Follow the existing backlog entries. TODO.md:L60-L62, docs/methodology/REGISTRY.md:L7304-L7317

Security

No findings.

Documentation/Tests

The changelog validator passed, and all changed Python files compiled. Isolated checks with test doubles reproduced the empty-input exception and verified the dCDH plotting and report behavior. The environment lacked the dependencies for the full test suite and could not reach the NBER PDF. The methodology cross-check used the Registry, the checked-in R reference, and the repository’s paper reviews.

Path to Approval

  1. Add an empty-panel guard before survey resolution. Add a public fit() regression test using a zero-row frame with unit, period, first_treat, outcome, and N columns and SurveyDesign(fpc="N"). Assert that it raises a descriptive ValueError.

@github-actions

Copy link
Copy Markdown

🔁 AI review rerun (requested by @igerber)

Head SHA: 63a8b068b930f2bf272670de3db958141bbe372e


Overall assessment

✅ Looks good. The prior P1 is resolved. Empty panels now raise a descriptive ValueError before survey design resolution, including the FPC-only case that previously raised IndexError. No unmitigated P0 or P1 findings remain. diff_diff/stacked_did.py:L534-L548

Executive summary

  • The public fit() regression test covers four empty-panel configurations, including the prior FPC-only failure. tests/test_stacked_did.py:L789-L815
  • StackedDiD applies the documented anticipation cutoff in both the inclusion check and stack construction. diff_diff/stacked_did.py:L1688-L1753, diff_diff/stacked_did.py:L1809-L1815
  • Taylor linearization counts original units as implicit PSUs. At zero survey degrees of freedom, the overall and event-time t-statistics, p-values, and confidence bounds are all NaN. diff_diff/stacked_did.py:L1263-L1307, diff_diff/stacked_did.py:L1329-L1379, diff_diff/stacked_did.py:L1428-L1467
  • The generic and dCDH plotting routes preserve undefined intervals. BusinessReport checks stored bounds and p-values independently. diff_diff/visualization/_event_study.py:L337-L365, diff_diff/business_report.py:L745-L813

Methodology

  • P3 · Documented anticipation extension. Impact. The default cutoff matches the checked-in R reference for Wing et al. With anticipation, a later cohort qualifies only if its response begins after the focal window closes. The strict rule also keeps the expanded windows disjoint. Concrete fix. None required. benchmarks/R/benchmark_stacked_did.R:L23-L42, docs/methodology/REGISTRY.md:L2599-L2608, docs/methodology/REGISTRY.md:L2636
  • P3 · Documented survey inference. Impact. Summing stacked scores within each original PSU follows Binder’s design-based variance formulation. The survey refusal prevents cutoff-induced sample loss from changing the variance calculation, and passing zero degrees of freedom to safe_inference prevents spurious t-based inference. Concrete fix. None required. docs/methodology/papers/binder-1983-review.md:L86-L104, docs/methodology/REGISTRY.md:L2636-L2638, diff_diff/stacked_did.py:L699-L719, diff_diff/utils.py:L404-L413

Code Quality

No open findings. An isolated check confirmed that all four empty-panel configurations exit before the survey resolver is reached. diff_diff/stacked_did.py:L534-L548, tests/test_stacked_did.py:L806-L815

Performance

No findings.

Maintainability

No open findings. The shared report helper uses the fitted result’s cutoff record and labels the earlier rule unverified when that record is absent. diff_diff/_reporting_helpers.py:L183-L220

Tech Debt

  • P3 · Tracked follow-ups. Impact. Plotly can still shade across a missing interval. TODO.md also tracks full-design survey inference for units outside the stack and SunAbraham’s zero-df fallback. Concrete fix. Break Plotly bands at undefined rows, preserve the full survey design in domain inference, and align SunAbraham’s aggregate and cell inference at zero df in the tracked follow-ups. TODO.md:L60-L62, docs/methodology/REGISTRY.md:L7304-L7317

Security

No findings.

Documentation/Tests

The changelog fragment passed validation, all nine changed Python files compiled, and isolated checks passed for the empty-panel guard, cutoff boundaries, NaN inference, plot inputs, and report wording. The environment lacked the scientific Python dependencies for the full suite and could not reach the NBER PDF. The methodology cross-check used the Registry, the checked-in R reference, and the repository’s Binder paper review. changelog.d/20261127-stacked-did-anticipation-survey.md:L1-L84

@igerber igerber added the ready-for-ci Triggers CI test workflows label Nov 27, 2026
@igerber
igerber merged commit 73395a8 into main Nov 27, 2026
43 of 44 checks passed
@igerber
igerber deleted the fix/stacked-did-anticipation-survey branch November 27, 2026 17:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-ci Triggers CI test workflows

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant